<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      let tree = {
        val: 1,
        left: {
          val: 2,
          left: {
            val: 4
          },
          right: {
            val: 5
          }
        },
        right: {
          val: 3,
          left: {
            val: 6
          }
        }
      }
      var flatten = function (root) {
        let result = []
        function preOrder(root) {
          if (!root) return null
          result.push(root)
          preOrder(root.left)
          preOrder(root.right)
        }
        preOrder(root)
        let head = { val: 0, left: null, right: null }
        let p = head
        for (let i = 0; i < result.length; i++) {
          p.right = result[i]
          p.left = null
          p = p.right
        }
        return head.right
      }
      console.log(flatten(tree))
    </script>
  </body>
</html>
